import React, { useState, useEffect, useRef, useContext } from 'react'
import { Table, Button, Modal, message, Input, Form } from 'antd'
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import axios from 'axios'
const EditableContext = React.createContext(null);

const { confirm } = Modal;

export default function NewsCategy() {
  // 初始化数据数组
  const [dataSource, setdataSource] = useState([])
  // 获取数据
  useEffect(() => {
    axios.get('/categories').then(res => {
      console.log(res.data);
      setdataSource(res.data)
    })
  }, [])
  
  // table表格头部定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      key: 'title',
      onCell: (record) => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave,
      }),
    },
    {
      title: '操作',
      key: 'pagepermisson',
      render: (item) => {
        return <div>
          <Button type="primary" onClick={()=>removeConfim(item)} danger shape="circle" icon={<DeleteOutlined />} />
        </div>
      }
    },
  ];
  const handleSave = (item) => {
    setdataSource(dataSource.map(data => {
      if (data.id === item.id) {
        return {
          id: data.id,
          title: item.title,
          value: item.title
        }
      }
      return data
    }))
    axios.patch(`/categories/${item.id}`, {
      title: item.title,
      value: item.value
    })
  }
  
  // 删除事件二次确认
  const removeConfim = item => {
    confirm({
      title: '您确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      cancelText: '取消',
      onOk() {
        removeMethed(item)
      },
      onCancel() {},
    });
  }
  // 删除的函数
  const removeMethed = item => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/categories/${item.id}`).then(res => {
      if (res.status === 200) {
        message.success('删除成功');
      }
    })
  }
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
  
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
  
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
  
    let childNode = children;
  
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
  
    return <td {...restProps}>{childNode}</td>;
  };
  
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} pagination={{
        pageSize: 10
      }}
        rowKey={(item) => item.id}
        components={{
          body: {
            row: EditableRow,
            cell: EditableCell,
          },
        }}
      ></Table>
    </div>
  )
}
